package net.lookyou.boot.demo.config.security;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import net.lookyou.boot.demo.entity.SysRole;
import net.lookyou.boot.demo.entity.SysUser;
import net.lookyou.boot.demo.entity.SysUserRole;
import net.lookyou.boot.demo.mapper.RoleMapper;
import net.lookyou.boot.demo.mapper.UserMapper;
import net.lookyou.boot.demo.mapper.UserRoleMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;

/**
 *  <p> 自定义userDetailsService - 认证用户详情 </p>
 *
 * @description :
 * @author : zhengqing
 * @date : 2019/10/14 10:33
 */
@Service
public class CustomerUserDetailsService implements UserDetailsService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private RoleMapper roleMapper;
    @Resource
    private UserRoleMapper userRoleMapper;

    /***
     * 根据账号获取用户信息
     * @param username:
     * @return: org.springframework.security.core.userdetails.UserDetails
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Collection<GrantedAuthority> authorities = new ArrayList<>();

        // 从数据库中取出用户信息
        SysUser user = userMapper.selectOne(new SysUser(){{
            setUsername(username);
        }});

        if(!Objects.nonNull(user) || StringUtils.isBlank(user.getPassword())){
            throw new UsernameNotFoundException("用户名不存在");
        }

        // 添加权限
        List<SysUserRole> sysUserRoleList = userRoleMapper.selectList(new EntityWrapper<SysUserRole>().eq("user_id", user.getId()));
        for (SysUserRole userRole : sysUserRoleList) {
            SysRole role = roleMapper.selectById(userRole.getRole_Id());
            authorities.add(new SimpleGrantedAuthority(role.getName()));
        }
        // 返回UserDetails实现类
        return new User(user.getUsername(), user.getPassword(), authorities);
    }

}
